/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { message } from "antd";
import {
  getValuationList,
  changeValuation,
  deleteValuation,
  saveValuation
} from "@/services/delivery";
import {
  isArray
} from "@/utils/utils";

export default {
  namespace: "valuation",
  state: {
    valuationList: {},
    singleValuation: null
  },

  effects: {
    * getValuationList({}, { call, put }) {
      const { code, data } = yield call(getValuationList);
      if (code == 0 && isArray(data)) {
        yield put({
          type: "save",
          payload: {
            valuationList: {
              list: data,
              pagination: {
                count: data.length,
                size: 10
              }
            }
          }
        });
      }
    },
    * changeValuation({ payload }, { put, call, select }) {
      const { code, msg } = yield call(changeValuation, payload);
      if (code == 0) {
        // yield put({
        //   type: "getValuationList"
        // });
        let {
          valuationList: { list }
        } = yield select(_ => _.valuation);
        list.map(item => {
          if (payload.switch == "ON") {
            if (item.id == payload.id) {
              item.status = 1;
            } else {
              item.status = 0;
            }
          } else {
            if (item.id == payload.id) {
              item.status = 0;
            }
          }
        });
        //yield put({
        //  type: 'save',
        //  payload: {
        //    valuationList: {
        //      list,
        //    },
        //  },
        //});
      } else {
        message.error(msg);
      }
    },
    * deleteValuation({ payload }, { call, put, select }) {
      const { code, msg } = yield call(deleteValuation, payload);
      if (code == 0) {
        // yield put({
        //   type: "getValuationList"
        // });
        let {
          valuationList: { list }
        } = yield select(_ => _.valuation);
        for (let i = 0, len = list.length; i < len; i++) {
          const payloadId = payload.id;
          if (list[i].id == payloadId) {
            list.splice(i, 1);
            break;
          }
        }
        message.success('已删除')
      } else {
        message.error(msg);
      }
    },

    * saveValuation({ payload, callback }, { call, put }) {
      const { code, msg } = yield call(saveValuation, payload);
      if (code == 0) {
        message.success("设置成功");
      }
      callback(code, msg);
    }
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload
      };
    }
  }
};
